//
//  SchoolAddDetailViewController.swift
//  HoneyBee
//
//  Created by point on 2018/2/26.
//  Copyright © 2018年 point. All rights reserved.
//

import UIKit

import SwiftyJSON
import IQKeyboardManagerSwift

class SchoolAddDetailViewController: BaseViewController {
    private var disposal = Disposal()
    
    var currentModel = SchoolDetailModel()
    lazy var toolbar: RichEditorToolbar = {
        let toolbar = RichEditorToolbar(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 44))
        toolbar.options = RichEditorDefaultOption.my
        return toolbar
    }()
    
    lazy var editorView: RichEditorView = {
        let editorView = RichEditorView()
        return editorView
    }()
    
    fileprivate lazy var clickBtn: UIButton = {
        let clickBtn = UIButton(type: .custom)
        return clickBtn
    }()
    
    fileprivate var imageSize:CGSize =  CGSize()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        IQKeyboardManager.shared.enable = false
        IQKeyboardManager.shared.enableAutoToolbar = false
        title = "机构详情"
        view.backgroundColor = UIColor.init(hex: "f4f6f8")
        editorView.frame = CGRect(x: 10, y: LayoutCommon.navHeight + 10, width: self.view.bounds.width - 20, height: self.view.bounds.height - LayoutCommon.navHeight - 10)
        view.addSubview(editorView)
        editorView.delegate = self
        
        editorView.inputAccessoryView = toolbar
        editorView.placeholder = "输入内容吧"
        
        toolbar.delegate = self
        toolbar.editor = editorView
        self.view.bringSubviewToFront(self.navgationBar)
        
        let itemEmpty = RichEditorOptionItem(image: nil, title: "清空") { toolbar in
            toolbar.editor?.html = ""
        }
        
        let itemDone = RichEditorOptionItem(image: nil, title: "完成") { toolbar in
            let _ = self.editorView.resignFirstResponder()
        }
        
        var options = toolbar.options
        options.append(itemEmpty)
        options.append(itemDone)
        toolbar.options = options
        
        
        NotificationCenter.default.addObserver(self, selector: #selector(kbFrameChanged(_:)), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
        
        view.addSubview(self.clickBtn)
        self.clickBtn.snp.makeConstraints { (make) in
            make.width.equalTo(250)
            make.bottom.equalToSuperview().inset(80)
            make.centerX.equalToSuperview()
            make.height.equalTo(30)
        }
        
        
        
        self.clickBtn.backgroundColor = UIColor.init(hex: "17bbfe")
        self.clickBtn.addTarget(self, action: #selector(clickNextBtn), for: .touchUpInside)
        clickBtn.fastCornerRadius(value: 15)
        addNavObserver()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        let _ = editorView.becomeFirstResponder()
    }
    
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillAppear(animated)
        IQKeyboardManager.shared.enable = true
        IQKeyboardManager.shared.enableAutoToolbar = true
    }
    
    @objc func kbFrameChanged(_ note : Notification) {
    }
    
    @objc fileprivate func clickNextBtn() {
        let current = String().currentTime()
        let html = currentModel.replacingHtml(editorView.contentHTML)
        let dict = [
            "address": currentModel.address,
            "globalAreaCode": currentModel.globalAreaCode,
            "headImg": currentModel.headImg,
            "info": html,
            "latitude": currentModel.latitude,
            "longitude": currentModel.longitude,
            "name": currentModel.name,
            "open":  currentModel.isOpen,
            "phone": currentModel.phone,
            "preferential": currentModel.preferential,
            "remark": currentModel.remark,
            "id": UserInfo.shareInstance.userModel().institutionId ,
            "userId": String(UserInfo.shareInstance.userModel().id),
            "isDelete":true
            ] as [String : Any]
        
        let api = kHost + kaddInstitution.apiF(time: current, sign: "")
        self.hudLoad()
        TempNetTool.post(api, parameters: dict, progress: nil, success: { [weak self] (result) in
            self?.hudHide()
            if self?.currentModel.modify == false {
                let vc = SchoolAddHornViewController()
                vc.schoolID = self?.currentModel.id ?? 0
                self?.navigationController?.pushViewController(vc, animated: true)
            }else {
                self?.navigationController?.popViewController(animated: true)
            }
        }) {  [weak self](error) in
            self?.hudHide()
            self?.hudLoadMessage("error")
        }
    }
}


// MARK:- 页面监听
extension SchoolAddDetailViewController {
    func addNavObserver() {
        self.dcObjcet?.observe({ [weak self] (curVal,PreVal) in
            guard let val = curVal as? SchoolDetailModel else  { return }
            self?.currentModel = val
            self?.editorView.html =  (self?.currentModel.info)!
            self?.clickBtn.setTitle( self?.currentModel.modify == false ? "下 一 步": "完 成", for: .normal)
        }).add(to: &disposal)
    }
}

// MARK:- 富文本代理
extension SchoolAddDetailViewController: RichEditorDelegate {
    func richEditorDidLoad(_ editor: RichEditorView) {
        editorView.setFontSize(15)
        editorView.setEditorFontColor(UIColor.black)
    }
    
    func richEditor(_ editor: RichEditorView, heightDidChange height: Int) {
        //print("zhaowang",self.editorView.contentHTML)
    }
    
    func richEditor(_ editor: RichEditorView, contentDidChange content: String) {
        
    }
}

extension SchoolAddDetailViewController: RichEditorToolbarDelegate {
    func richEditorToolbarInsertImage(_ toolbar: RichEditorToolbar) {
        
        openImagePicker()
    }
}

// MARK:- 图片代理
extension SchoolAddDetailViewController:UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    fileprivate func photoClick() {
        if !UIImagePickerController.isSourceTypeAvailable(.photoLibrary)  { return }
        let photoVc = UIImagePickerController()
        photoVc.sourceType = .photoLibrary
        photoVc.delegate = self
        present(photoVc, animated: true, completion: nil)
    }
    
    fileprivate func cameraClick() {
        let pick:UIImagePickerController = UIImagePickerController()
        pick.delegate = self
        pick.sourceType = UIImagePickerController.SourceType.camera
        pick.allowsEditing = true
        present(pick, animated: true, completion: nil)
        
    }
    func openImagePicker() {
        let alertVc = UIAlertController(title: "选择来源?", message: nil, preferredStyle: .actionSheet)
        let photoAction = UIAlertAction(title: "从相册选取", style: .default) { (_) in
            self.photoClick()
        }
        let cameraAction = UIAlertAction(title: "相机", style: .default) { (_) in
            self.cameraClick()
        }
        let cancelAction = UIAlertAction(title: "取消", style: .default) { (_) in}
        alertVc.addAction(photoAction)
        alertVc.addAction(cameraAction)
        alertVc.addAction(cancelAction)
        present(alertVc, animated: true, completion: nil)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        
        
        
        
        
        picker.dismiss(animated: true, completion: nil)
        
        guard let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage else { return }
        
        
        
        imageSize = image.size
        
        let imgData = image.jpegData(compressionQuality: 0.5)
        
        
        self.hudLoad("上传中 请稍后")
        TempNetTool.get(kHost + kgetImgToken, parameters: ["timestamp":"11","sign":"22"], progress: nil, success: { (result) in
            let json = JSON(result ?? "")
            let token = json["uptoken"].string
            let upManager = QNUploadManager()
            upManager?.put(imgData, key: nil, token: token, complete: { [unowned self](info, key, resp) in
                self.hudHide()
                let json = JSON(resp as Any)
                let url = json["key"].stringValue
                if url.count > 0 {
                    var maxW = 0
                    if self.imageSize.width > kScreenW - 20 {
                        maxW = Int(kScreenW - 20)
                    }else {
                        maxW = Int(self.imageSize.width)
                    }
                    let height = CGFloat(maxW) * self.imageSize.height /  self.imageSize.width
                    self.toolbar.editor?.insertImage(kqnImageHost + url, alt: "图片", width: String(maxW), height: String(Int(height)))
                }else {
                    self.hudLoadMessage("网络异常")
                }
                
                }, option: nil)
        }) { [weak self](error) in
            self?.hudHide()
            self?.hudLoadMessage("网络异常")
        }
    }
}

//smith add new extension for My option.
extension RichEditorDefaultOption {
    public static let my: [RichEditorDefaultOption] = [
        .alignLeft, .alignCenter, .alignRight, .image,.undo, .redo,
        ]
}

